using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.Core;

namespace Forum.Business
{
    public class MyThreadEdit : ForumUserControl,
        IReplyConverter<ThreadReply, GetOperation>
    {
        protected ValuedTextBox subjectTextBox;
        protected ValuedTextBox threadMarksTextBox;
        protected ValuedEditor bodyEditor;
        protected ResourceButton saveButton;

        private Thread thread;

        public override void GetRequests(List<BaseRequestBinder> requestBinders)
        {
            requestBinders.Add(RequestHelper.BuildGetThreadRequest(this));
        }

        protected override void OnLoad(EventArgs e)
        {
            saveButton.Click += new EventHandler(SaveThread);
        }

        private void BindData()
        {
            if (thread != null)
            {
                if (!ValidatePermission(PermissionType.EditThread, thread))
                {
                    throw new Exception("Access denied.");
                }
                subjectTextBox.Value = thread.Subject.Value;
                threadMarksTextBox.Value = thread.ThreadMarks.Value.ToString();
                bodyEditor.Value = thread.Body.Value;
            }
        }
        private void SaveThread(object sender, EventArgs e)
        {
            if (thread != null)
            {
                thread.Subject.Value = subjectTextBox.Value;
                thread.ThreadMarks.Value = int.Parse(threadMarksTextBox.Value);
                thread.Body.Value = bodyEditor.Value;

                BusinessManager.UpdateThread(thread);
            }

            Page.Response.Redirect(UrlManager.Instance.FormatUrl("myopenthreadlist", CurrentUser.EntityId.Value));
        }

        #region IReplyConverter<ThreadReply,GetOperation> Members

        public void ConvertReply(ThreadReply reply, GetOperation operation)
        {
            if (reply != null)
            {
                thread = reply.Entity as Thread;

                if (!IsPostBack)
                {
                    BindData();
                }
            }
        }

        #endregion
    }
}